use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashMap;

/// 连接器运行时配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConnectorRuntimeConfig {
    /// 连接器ID
    pub connector_id: String,
    /// 连接器类型
    pub connector_type: String,
    /// 连接器配置
    pub config: Value,
    /// 运行时参数
    pub runtime_params: RuntimeParams,
}

/// 运行时参数
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RuntimeParams {
    /// 批次大小
    pub batch_size: usize,
    /// 轮询间隔（秒）
    pub poll_interval: u64,
    /// 最大重试次数
    pub max_retries: u32,
    /// 重试间隔（秒）
    pub retry_interval: u64,
    /// 超时时间（秒）
    pub timeout: u64,
    /// 并发度
    pub concurrency: u32,
    /// 缓冲区大小
    pub buffer_size: usize,
    /// 是否启用指标收集
    pub enable_metrics: bool,
    /// 自定义标签
    pub labels: HashMap<String, String>,
}

impl Default for RuntimeParams {
    fn default() -> Self {
        Self {
            batch_size: 1000,
            poll_interval: 60,
            max_retries: 3,
            retry_interval: 5,
            timeout: 30,
            concurrency: 1,
            buffer_size: 10000,
            enable_metrics: true,
            labels: HashMap::new(),
        }
    }
}

/// 连接器配置验证器
pub struct ConfigValidator;

impl ConfigValidator {
    /// 验证连接器配置
    pub fn validate_config(connector_type: &str, config: &Value) -> Result<(), String> {
        match connector_type {
            "http" => Self::validate_http_config(config),
            "database" => Self::validate_database_config(config),
            "file" => Self::validate_file_config(config),
            _ => Err(format!("未知的连接器类型: {}", connector_type)),
        }
    }
    
    /// 验证HTTP连接器配置
    fn validate_http_config(config: &Value) -> Result<(), String> {
        let obj = config.as_object()
            .ok_or("配置必须是对象格式")?;
        
        // 验证必需字段
        if !obj.contains_key("url") {
            return Err("缺少必需字段: url".to_string());
        }
        
        let url = obj.get("url").unwrap().as_str()
            .ok_or("url字段必须是字符串")?;
        
        if url.is_empty() {
            return Err("url不能为空".to_string());
        }
        
        // 验证URL格式
        if !url.starts_with("http://") && !url.starts_with("https://") {
            return Err("url必须以http://或https://开头".to_string());
        }
        
        // 验证HTTP方法
        if let Some(method) = obj.get("method") {
            let method_str = method.as_str()
                .ok_or("method字段必须是字符串")?;
            
            if !["GET", "POST", "PUT", "DELETE", "PATCH"].contains(&method_str.to_uppercase().as_str()) {
                return Err("不支持的HTTP方法".to_string());
            }
        }
        
        // 验证轮询间隔
        if let Some(interval) = obj.get("poll_interval") {
            let interval_num = interval.as_u64()
                .ok_or("poll_interval字段必须是正整数")?;
            
            if interval_num == 0 {
                return Err("poll_interval必须大于0".to_string());
            }
        }
        
        Ok(())
    }
    
    /// 验证数据库连接器配置
    fn validate_database_config(config: &Value) -> Result<(), String> {
        let obj = config.as_object()
            .ok_or("配置必须是对象格式")?;
        
        // 验证必需字段
        if !obj.contains_key("connection_url") {
            return Err("缺少必需字段: connection_url".to_string());
        }
        
        let connection_url = obj.get("connection_url").unwrap().as_str()
            .ok_or("connection_url字段必须是字符串")?;
        
        if connection_url.is_empty() {
            return Err("connection_url不能为空".to_string());
        }
        
        // 验证查询SQL（对于数据源）
        if let Some(query) = obj.get("query") {
            let query_str = query.as_str()
                .ok_or("query字段必须是字符串")?;
            
            if query_str.trim().is_empty() {
                return Err("query不能为空".to_string());
            }
        }
        
        // 验证表名（对于目标）
        if let Some(table_name) = obj.get("table_name") {
            let table_str = table_name.as_str()
                .ok_or("table_name字段必须是字符串")?;
            
            if table_str.trim().is_empty() {
                return Err("table_name不能为空".to_string());
            }
        }
        
        Ok(())
    }
    
    /// 验证文件连接器配置
    fn validate_file_config(config: &Value) -> Result<(), String> {
        let obj = config.as_object()
            .ok_or("配置必须是对象格式")?;
        
        // 验证必需字段
        if !obj.contains_key("path") {
            return Err("缺少必需字段: path".to_string());
        }
        
        let path = obj.get("path").unwrap().as_str()
            .ok_or("path字段必须是字符串")?;
        
        if path.is_empty() {
            return Err("path不能为空".to_string());
        }
        
        // 验证文件格式
        if let Some(format) = obj.get("format") {
            let format_str = format.as_str()
                .ok_or("format字段必须是字符串")?;
            
            if !["json", "jsonlines", "csv", "text", "xml"].contains(&format_str.to_lowercase().as_str()) {
                return Err("不支持的文件格式".to_string());
            }
        }
        
        Ok(())
    }
}

/// 配置模板生成器
pub struct ConfigTemplateGenerator;

impl ConfigTemplateGenerator {
    /// 生成连接器配置模板
    pub fn generate_template(connector_type: &str) -> Value {
        match connector_type {
            "http" => Self::http_template(),
            "database" => Self::database_template(),
            "file" => Self::file_template(),
            _ => serde_json::json!({}),
        }
    }
    
    /// HTTP连接器配置模板
    fn http_template() -> Value {
        serde_json::json!({
            "url": "https://api.example.com/data",
            "method": "GET",
            "headers": {
                "Content-Type": "application/json",
                "Authorization": "Bearer YOUR_TOKEN"
            },
            "poll_interval": 60,
            "timeout": 30,
            "auth": {
                "type": "bearer",
                "token": "YOUR_TOKEN"
            },
            "pagination": {
                "type": "page",
                "page_param": "page",
                "page_size_param": "limit",
                "page_size": 100
            },
            "data_path": "data"
        })
    }
    
    /// 数据库连接器配置模板
    fn database_template() -> Value {
        serde_json::json!({
            "connection_url": "postgresql://username:password@localhost:5432/database",
            "query": "SELECT * FROM your_table WHERE updated_at > $1",
            "poll_interval": 300,
            "batch_size": 1000,
            "incremental": {
                "cursor_field": "updated_at",
                "cursor_type": "timestamp"
            }
        })
    }
    
    /// 文件连接器配置模板
    fn file_template() -> Value {
        serde_json::json!({
            "path": "/path/to/your/files",
            "format": "jsonlines",
            "encoding": "utf-8",
            "watch_mode": true,
            "poll_interval": 60,
            "file_pattern": "*.json",
            "recursive": false
        })
    }
}
